# -*- coding: utf-8 -*-
# created by Alberthch - 陈航  2021/7/15 20:33
# Description:你有一个字典或者实例的序列，然后你想根据某个特定的字段比如date来分组迭代访问
from itertools import groupby
from collections import defaultdict
from pprint import pprint

rows = [
    {'address': '5412 N CLARK', 'date': '07/01/2012'},
    {'address': '5148 N CLARK', 'date': '07/04/2012'},
    {'address': '5800 E 58TH', 'date': '07/02/2012'},
    {'address': '2122 N CLARK', 'date': '07/03/2012'},
    {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
    {'address': '1060 W ADDISON', 'date': '07/02/2012'},
    {'address': '4801 N BROADWAY', 'date': '07/01/2012'},
    {'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]
# 首先进行指定字段进行排序sorted和.sort，两种函数，序列的.sort，原地排序
rows.sort(key=lambda r: r['date'])
# 然后调用itertools中的groupby函数
for date, items in groupby(rows, key=lambda r: r['date']):
    print(date)
    for i in items:
        print('    ', i)
print("="*20)

# Example of building a multidict


rows_by_date = defaultdict(list)
for row in rows:
    rows_by_date[row['date']].append(row)
pprint(rows_by_date)

for r in rows_by_date['07/01/2012']:
    print(r)
